package com.jiyi.activity.datainput.sm;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jiyi.bean.datainput.DataInputBaseBean;
import com.jiyi.bean.datainput.new_input.DetailBuildBean;
import com.jiyi.exception.SampleProgressObserver;
import com.jiyi.inteface.DeletePopInterface;
import com.jiyi.inteface.SygnPopInterface;
import com.jiyi.retrofit.HttpMethods;
import com.jiyi.view.DataInputSygnPopView;
import com.jiyi.view.DeletePopView;
import com.jiyi.widget.AutoLinefeedLayout;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/3/22.
 */

public class BuildDetailInfoActivity extends ActivityBase implements SygnPopInterface, DeletePopInterface {

    /* 头部 */
    @BindView(R.id.tvBack)
    TextView tvBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSearch)
    TextView tvSearch;

    @BindView(R.id.rbOne)
    RadioButton rbOne;
    @BindView(R.id.rbTwo)
    RadioButton rbTwo;
    @BindView(R.id.rbZhuZhai)
    RadioButton rbZhuZhai;
    @BindView(R.id.rbGongJian)
    RadioButton rbGongJian;
    @BindView(R.id.rgBuildCat)
    RadioGroup rgBuildCat;
    @BindView(R.id.rgBuildCatTwo)
    RadioGroup rgBuildCatTwo;
    @BindView(R.id.etHeight)
    EditText etHeight;
    @BindView(R.id.etDSCS)
    EditText etDSCS;
    @BindView(R.id.etDXCS)
    EditText etDXCS;
    @BindView(R.id.etDSMJ)
    EditText etDSMJ;
    @BindView(R.id.etDXMJ)
    EditText etDXMJ;
//    @BindView(R.id.llSYC)
//    LinearLayout llSYC;
    @BindView(R.id.etBNCWZ)
    EditText etBNCWZ;
    @BindView(R.id.etUserFunc)
    EditText etUserFunc;
    @BindView(R.id.etOther)
    EditText etOther;
    @BindView(R.id.etControlLocal)
    EditText etControlLocal;
    @BindView(R.id.allXFSS)
    AutoLinefeedLayout allXFSS;

    DataInputSygnPopView mDataInputSygnPopView;
    DeletePopView mDeletePopView;
    LayoutInflater inflater;

    View deleteView = null;
    List<DataInputBaseBean.ZYXFSS> dataList = new ArrayList<DataInputBaseBean.ZYXFSS>();
    int mBuildType=1;
    int mBuildTypeTwo=1;

    String build_id = "";
    final String[] items = new String[]{"自动喷水灭火系统", "火灾自动报警系统", "水喷雾灭火系统", "室内消火栓",
            "室外消火栓", "机械防烟设施", "机械排烟设施", "应急广播", "应急照明", "消防电梯","气体灭火系统"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_build_detail_info);
        ButterKnife.bind(this);
        mDataInputSygnPopView = new DataInputSygnPopView(this, this);
        mDeletePopView = new DeletePopView(this, this);
        inflater = LayoutInflater.from(this);
        init();
    }


    public void init() {
        getIntentData();
        setTop();
        setViewStatus();
        getData();
    }

    private void getIntentData() {
        build_id = getIntent().getStringExtra("build_no");
        if (TextUtils.isEmpty(build_id))
            build_id = "";
    }

    private void setTop() {
        tvTitle.setText("建筑详细情况");
        tvSearch.setCompoundDrawables(null, null, null, null);
        tvSearch.setText("保存");
    }

    public void setViewStatus()
    {
        rgBuildCat.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbOne)
                {
                    mBuildType = 1;
                } else if (checkedId == R.id.rbTwo) {
                    mBuildType=2;
                }
            }
        });

        rgBuildCatTwo.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rbZhuZhai)
                {
                    mBuildTypeTwo = 1;
                }
                else
                {
                    mBuildTypeTwo = 2;
                }

            }
        });
    }


    public void getData(){
        HttpMethods.getInstance().getDetailBuildInfo(UserInfoUtil.getCurrentUserAccessToken(),build_id,2)
                .subscribe(new SampleProgressObserver<DetailBuildBean>(this) {
                    @Override
                    public void onNext(DetailBuildBean o) {
                        if (o == null || "".equals(o.getGson_null()))
                        {
                            o = new DetailBuildBean();
                            o.setCategory(1);
                            o.setCategory_o(1);
                            o.setHeight("");
                            o.setPlies_num("");
                            o.setUp_area("");
                            o.setDown_area("");
                            o.setUse_for("");
                            o.setRefuge_storey("");
//                            StringBuilder stringBuilder = new StringBuilder();
//                            for (int i = 0 ;i<items.length;i++)
//                            {
//                                stringBuilder.append("0").append(",");
//                            }
//                            o.setFighting_device(stringBuilder.toString().substring(0,stringBuilder.toString().length()-1));
                            o.setFighting_device("");
                            o.setO_fighting_device("");
                            o.setControl_room_area("");
                            o.setNo_edit(1);
                        }
                        fillData(o);
                    }
                });
    }

    private void fillData(DetailBuildBean detailBuildBean)
    {

        System.out.println("detailBuildBean.getCategory():" + detailBuildBean.getCategory());

        if (detailBuildBean.getCategory_o() == 1)
        {
            rbOne.setChecked(true);
        }
        else
        {
            rbTwo.setChecked(true);
        }

        System.out.println("detailBuildBean.getCategory_o():" + detailBuildBean.getCategory_o());


        if (detailBuildBean.getCategory() == 1)
        {
            rbZhuZhai.setChecked(true);
        }
        else {
            rbGongJian.setChecked(true);
        }

        etHeight.setText(detailBuildBean.getHeight());
        etDSCS.setText(detailBuildBean.getUp_storey());
        etDXCS.setText(detailBuildBean.getDown_storey());
        etDSMJ.setText(detailBuildBean.getUp_area());
        etDXMJ.setText(detailBuildBean.getDown_area());
        etUserFunc.setText(detailBuildBean.getUse_for());
        etBNCWZ.setText(detailBuildBean.getRefuge_storey());
        boolean[] status = new boolean[items.length];
        for (int i=0;i<items.length;i++)
        {
            status[i] = false;
        }
        if (!TextUtils.isEmpty(detailBuildBean.getFighting_device()))
        {
            System.out.println("detailBuildBean.getFighting_device():" + detailBuildBean.getFighting_device());

            String[] strStatus = detailBuildBean.getFighting_device().split(",");
            for (int i = 0;i<strStatus.length;i++)
            {
                for (int j = 0;j<items.length;j++)
                {
                    if (strStatus[i].equals(String.valueOf(j+1)))
                    {
                        status[j] = true;
                        break;
                    }
                }
            }
        }

        Log.e("status " ,status.toString());

        initSFSS(status);
        etOther.setText(detailBuildBean.getO_fighting_device());
        etControlLocal.setText(detailBuildBean.getControl_room_area());

        if (detailBuildBean.getNo_edit() == 1)
        {
            tvSearch.setVisibility(View.VISIBLE);
        }
        else
        {
            tvSearch.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void OnSureAddListener(String text) {
//        View item = inflater.inflate(R.layout.item_data_input_sygn, null, false);
//
//        ImageView ivDelete = item.findViewById(R.id.tvSYGN_SHANCHU);
//        ivDelete.setTag(item);
//        TextView tvSYGN_MIAOSHU = item.findViewById(R.id.tvSYGN_MIAOSHU);
//
//        ivDelete.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                deleteView = (View) v.getTag();
//                mDeletePopView.showPopWindow();
//            }
//        });
//
//        tvSYGN_MIAOSHU.setText(text);
//
//        llSYC.addView(item);
//        mDataInputSygnPopView.hidePopWindow();
    }

    @Override
    public void OnCancleAddListener() {


    }

    @Override
    public void OnDeleteListener() {
//        if (deleteView == null)
//            return;
//        llSYC.removeView(deleteView);
//        deleteView = null;
//        mDeletePopView.hidePopWindow();
    }

    @Override
    public void OnCancleListener() {

    }

    @Override
    public void OnShowListener() {

    }

    @Override
    public void OnHideListener() {

    }

    private void initSFSS(final boolean[] status) {

        allXFSS.removeAllViews();
        Observable.range(0, 11)
                .map(new Function<Integer, DataInputBaseBean.ZYXFSS>() {
                    @Override
                    public DataInputBaseBean.ZYXFSS apply(Integer integer) throws Exception {
                        DataInputBaseBean.ZYXFSS zyxfss = new DataInputBaseBean.ZYXFSS();
                        zyxfss.setId(integer+1);
                        zyxfss.setName(items[integer]);
                        zyxfss.setCheck(status[integer]);
                        dataList.add(zyxfss);
                        return zyxfss;
                    }
                })
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataInputBaseBean.ZYXFSS>() {
                    @Override
                    public void accept(DataInputBaseBean.ZYXFSS zyxfss) throws Exception {
                        View item = inflater.inflate(R.layout.item_text_checkbox, null, false);
                        item.setTag(zyxfss);
                        TextView tvName = item.findViewById(R.id.tvName);
                        tvName.setText(zyxfss.getName());
                        CheckBox cbXFSS = item.findViewById(R.id.checkBox);
                        cbXFSS.setChecked(zyxfss.isCheck());

                        item.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DataInputBaseBean.ZYXFSS clickItem = (DataInputBaseBean.ZYXFSS) v.getTag();
                                CheckBox checkBox = v.findViewById(R.id.checkBox);
                                if (clickItem.isCheck()) {
                                    clickItem.setCheck(false);
                                    checkBox.setChecked(false);
                                } else {
                                    clickItem.setCheck(true);
                                    checkBox.setChecked(true);
                                }
                            }
                        });
                        allXFSS.addView(item);
                    }
                });

    }


    @OnClick({R.id.tvBack, R.id.tvSearch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvBack:
                finish();
                break;
            case R.id.tvSearch:
                doPost();
                break;
//            case R.id.tvAddSygn:
//                mDataInputSygnPopView.showPopWindow();
//                break;
            default:
                break;
        }
    }

    private void doPost() {

        System.out.println("mBuildType: " + mBuildType);
        System.out.println("mBuildTypeTwo: " + mBuildTypeTwo);

        Map<String,String> params = new HashMap<>();
        params.put("category",mBuildType+"");
        params.put("category_o",mBuildTypeTwo+"");
        params.put("height",etHeight.getText().toString());
        params.put("up_storey",etDSCS.getText().toString());
        params.put("down_storey",etDXCS.getText().toString());
        params.put("up_area",etDSMJ.getText().toString());
        params.put("down_area",etDXMJ.getText().toString());
        params.put("use_for",etUserFunc.getText().toString());
        params.put("refuge_storey",etBNCWZ.getText().toString());

        StringBuilder sb = new StringBuilder();
        for (DataInputBaseBean.ZYXFSS zyxfss : dataList)
        {
            if (zyxfss.isCheck())
            {
                sb.append(zyxfss.getId()).append(",");
            }

        }
        String fighting_device = TextUtils.isEmpty(sb.toString()) ? "" : sb.toString().substring(0,sb.toString().length()-1);


        params.put("fighting_device",fighting_device);
        params.put("o_fighting_device",etOther.getText().toString());
        params.put("control_room_area",etControlLocal.getText().toString());

        HttpMethods.getInstance().postDetailBuildInfo(UserInfoUtil.getCurrentUserAccessToken(),build_id,1, new Gson().toJson(params))
                .subscribe(new SampleProgressObserver<DetailBuildBean>(this) {
                    @Override
                    public void onNext(DetailBuildBean o) {
                        ToastUtil.getInstances().showMsg("保存成功");
                    }
                });
    }
}
